<?php

namespace app\api\middleware;

// 中间件
use app\BaseController;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use think\Exception;
use think\facade\Db;
use think\Response;

class ApiToken extends BaseController
{
    //解析Token
    public function handle($request, \Closure $next)
    {
        try {
            //接收token
            $token = $request->header('Authorization');
            if (empty($token)) {
                return Response::create(['error' => '请先登录！'], 'json', 401);
            }
            //加载配置项JWT Key
            $test = JWT::decode($token, new Key(config('app.jwtKey'), 'HS256'));
            $request->user_id = $test->data->user_id;
//            $request->mobile = $test->data->mobile;
            return $next($request);
        } catch (SignatureInvalidException $signatureInvalidException) {
            return Response::create(['error' => '身份信息验证失败,请重新登录!'], 'json', 401);
        } catch (ExpiredException $expiredException) {
            return Response::create(['error' => '登录信息过期，请重新登录!'], 'json', 401);
        } catch (Exception $exception) {
            return Response::create(['error' => $exception->getMessage()], 'json', 500);
        }
    }

}